<template>
  <div class="calendar_m">
    <div class="calendar_t">
      <i class="fa fa-chevron-left text-black icon-zuobian" @click="prevBtn"></i>
      <div class="calendar_t_m swiper-container1">
        <div class="swiper-wrapper" style="height: 40px; transition-duration: 0s; transform: translate3d(0px, 0px, 0px);">
          <div v-for="(data, index) in schedulePrintMin" 
            :key="index" 
            :data-index="index" 
            :data-date="data.date"
            :class="index == calendarData.index ? 'swiper-slide-active active' : ''"
            class="li swiper-slide swiper-slide-visible" 
            @click="calendar(index)"
          >
            <p>{{data.date}}</p>
            <span v-if="data.price > 0"> ¥{{data.price}}起 </span>
            <span v-else>暂无排期</span>
          </div>
        </div>
      </div>
      <i class="fa fa-chevron-right text-black icon-youbian" @click="nextBtn"></i>
    </div>
    <div class="calendar">
      <div class="box-center">
        <div class="cal-head" data-yearmonth="2023-8"><span>2023年8月</span></div>
        <ul class="week-list">
          <li>周日</li>
          <li>周一</li>
          <li>周二</li>
          <li>周三</li>
          <li>周四</li>
          <li>周五</li>
          <li>周六</li>
        </ul>
        <div class="calendar-box">
          <ul class="day-list">
            <li class="new" v-for="num in calendarData.curMonthWeek" :key="num"></li>
            <li rel="targetBox" v-for="num in calendarData.curMonthDate" 
              :key="num + calendarData.curMonthWeek" 
              :class="{ 'active': calendarActive == num }"
              @click="SelectSchedule(num)"
              @mouseover="calendarData.targetBox = num"
              @mouseleave="calendarData.targetBox = ''"
            >
              <p class="text have-price" :class="{ 'have-price11': !!getScheduleData(num).price }">{{num}}<span class="style"></span></p>
              <div v-if="getScheduleData(num).price" class="scheduleInfo" style="font-size: 10px">
                <p class="price">
                  <span class="qi">¥</span>
                  <span class="jg">{{getScheduleData(num).price}}</span>
                  <span class="qi">起</span>
                </p>
                <p class="spare" style="margin-top: 5px">余位:<span class="style" style="color: #009f4d; font-size: 13px; font-weight: bold; ">{{ getScheduleData(num).seat > 0 ? getScheduleData(num).resi : "现询" }}</span></p>
                <!--div class="targetBox" :style="{display: calendarData.targetBox == num ? 'block' : 'none'}">
                  <div class="targetBox2" date-tuan="TS2400179805" data-route="A">
                    <div class="clear"><div class="tripstyle fl">A行程</div></div>
                    <p class="jiage"> <span>成人价4780</span></p>
                    <div class="data">2024-05-20 出发</div>
                  </div>
                  <div class="clear"></div>
                </div-->
              </div>
            </li>
            <li class="old" v-for="num in 42 - calendarData.curMonthWeek - calendarData.curMonthDate" 
              :key="num + calendarData.curMonthWeek + calendarData.curMonthDate">
            </li>
            <div class="clear"></div>
          </ul>
        </div>
      </div>
    </div>
  </div>
  <!--div class="mart10">
    <div class="remarks">*预定此路线，部分班期可以使用抵用券抵扣</div>
    <div class="remarks">*不同的出发班期，可以享受的优惠略有不同，请以实际选择的班期为准</div>
    <div class="remarks">*因数据更新时滞，具体以实际销售金额为准</div>
  </div-->
</template>
<script>
import { unixToDate } from '@/plugins/Foundation.js';
export default {
  props: {
    circular: {
      type: Boolean,
      default: false,
    },
    height: {
      type: String,
      default: "550",
    },
    // 产品数据
    data: {
      type: Array,
      default: null,
    },
    // 选中某天
    day: {
      type: String,
      default: '',
    },
    // 出港地
    post: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    // 获取传值价格排期
    skuCalendar () {
      return this.data;
    },
    /**
     * 说明：右边的下拉列表
     * 显示：年月 YM -> 日 D > datePriceDate
     */
    tourSelectData() {
      let result = []
      for (let [key, value] of Object.entries(this.tourData)) {
        for (let [k, v] of Object.entries(value)) {
          result.push(key + '-' + k + '(' + v.weekname + ')出发 - ' + v.price + '/人')
        }
      }
      console.info("tourSelectData@@", result)
      return result
    },
  },
  watch:{
    day(val){
      //console.info("watch@@@@", val);
      this.calendarActive = val
    },
    // 当有多个出港地
    post(val) {
      this.calendarData.post = val || 0;
      this.tourData = {}

      console.info("watch@@@@post", this.calendarData.post);

      this.tourDateData();
      // 延迟1秒执行这个匿名函数
      setTimeout(function() {
        //console.log("这个匿名函数将在1秒后执行");
        //this.tourDateData();
      }, 1000);
    }
  },
  data() {
    return {
      currentIndex: 0,
      currentId: "",
      //当前标签日期
      calendarData: {
        //出港
        post: 0,
        //序号
        index: -1,
        //某第一天日期
        NewDate: '',
        //年
        nYear: 0,
        //月
        nMonth: 0,
        //日
        nDay: 0,
        //某月第一天是星期几
        curMonthWeek: 0,
        //某月最后一天是几号
        curMonthDate: 0,
        //弹出描述
        targetBox: '',
      },
      calendarActive: '',
      // 
      schedulePrintMin: [
        { date: '2024-05', price: '5000' }, 
        { date: '2024-06', price: '6699' }
      ],
      //年月 - 日
      tourData: {
        '2024-05': {
          '10': { price: 5000, spare: '余位', priceVip: 200, priceRoom: 10, weekname: '周三', date: '2023-08-10' },
          '21': { price: 6699, spare: '余位', priceVip: 200, priceRoom: 10, weekname: '周三', date: '2023-08-21' }
        },
        '2024-06': {
          '08': { price: 6699, spare: '余位', priceVip: 200, priceRoom: 10, weekname: '周三', date: '2023-09-08' },
          '09': { price: 7899, spare: '余位', priceVip: 200, priceRoom: 10, weekname: '周三', date: '2023-09-09' }
        },
      },

      //选项卡当前数据
      scheduleData: {},
      scheduleShow: false,
      current_month: '请选择',
      scheduleActive: false,
    };
  },
  mounted(e) {
    //this.mySwiper1 = new Swiper('.swiper-container1', { slidesPerView: 5 })
    //console.info('mySwiper1@@@@', this.mySwiper1)  this.day
    this.tourDateData()
    this.calendarActive = 28;
  },
  methods: {
    /**
     * 1、第一层日期价格tab，最多5个，多出左右切换；点击下边日历格子里显示当前月排期价格；
     * 2、第二层显示周几
     * 3、第二层日历格子 7 x 6，计算1号为周几，就可以初始化格子日期了
     * 4、价格排期的数据结构 ｛｝
     * 5、事件
     * 6、点击某项排期，显示出团
     */


    //--数据初始化---------------------------------------------
    /**
     * 说明：价格排期 - 初始化默认值 mounted
     */
    async tourDateData() {
      //1、原始传值
      //this.ProductTourDates = cmsArticle['scheposts']
      var scheposts = this.skuCalendar;

      //2、从排期数据取出日期
      var arr1 = [], arr2 = [], list = [];
      if (scheposts && scheposts[this.calendarData.post]) {
        list = scheposts[this.calendarData.post].list;
        // 能过出团日期，得年-月， 然后分组
        list.filter((x, index, self) => arr1.push(x.tourDate.substring(0, 7)));
        arr2 = arr1.filter((x, index, self) => self.indexOf(x) === index) 
      }

      //console.info(arr2)
      
      //3、从排期日期取出最低价
      this.schedulePrintMin = [];
      arr2.forEach((a, i) => {
        var data = {}, price = 1000000;
        list.forEach((item, index) => {
          var mooth = item.tourDate.substring(0, 7)
          if (a == mooth && price > item.price) {
            price = item.price
            data = {
              date: mooth,
              price: price,
              priceChild: item.priceChild
            }
          }
        })
        this.schedulePrintMin.push(data);
      })
      
      //console.info("schedulePrintMin@@", this.schedulePrintMin);

      if (this.schedulePrintMin.length <= 0) {
        var data = {
          date: unixToDate(new Date(), 'yyyy-MM'),
          price: 0
        }
        this.schedulePrintMin.push(data);
      }

      //4、价格排期按年月 - 日，重新分级 this.tourData
      // this.tourData = {};
      // setTimeout(function() {
      //   this.tourData = list;
      // }, 1000);
      this.tourData = list;
      //5、初始日历 - 
      await this.calendar(0, 0)
    },

    /**
     * 说明：价格排期 - 给构建日历
     * 
     * @param index 年月
     * @param post    
     */
    async calendar(index, post) {
      /**
       * 当前月份
       * 当前出港
       */
      if (this.calendarData.index == index && this.calendarData.post == post) {
        // return;
      }

      //当前选中月份 -- 日历数据
      var data  = this.calendarData;
      var time  = this.schedulePrintMin[index].date;
      var price = this.schedulePrintMin[index].price
      var priceChild = this.schedulePrintMin[index].priceChild

      //当前选中月份 -- 排期价格
      await this.getTourData(time)

      data.index   = index;
      data.NewDate = new Date(time) ;
      data.nYear   = data.NewDate.getFullYear()+"";
      data.nMonth  = this.Lpad(data.NewDate.getMonth() + 1);
      data.nDay    = this.Lpad(data.NewDate.getDay());

      data.curMonthDate = this.getDayNum(data.nYear, data.nMonth);
      var newDate = new Date(data.nYear, data.nMonth - 1, 1);
      data.curMonthWeek = newDate.getDay();
      data.price        = price;
      data.priceChild   = priceChild;

      // 去掉日期的选中状态
      this.calendarActive = '';
      this.$emit('calendarTab', this.calendarData);
      //查看选中排期的参数
      //console.info('calendar2@@@', time, this.schedulePrintMin.length, data.curMonthDate, data.curMonthWeek)
    },

    /**
     * 说明：价格排期 - 获取某月份排期价格
     * @param time 年月
     */
    async getTourData(time) {
      // if (!this.tourData || this.tourData.indexOf("tourDate") == 0) {
      //   return
      // }
      this.scheduleData = this.tourData.filter((x) => x.tourDate && x.tourDate.indexOf(time) >= 0)
      //console.info("getTourData@@", this.scheduleData)
    },

    /**
     * 说明：计算某年某月的天数
     * @param num
     */
    calendarDataTime(num) {
      var nDate = '-1'
      if (this.calendarData) {
        nDate = this.calendarData.nYear + '-' + this.calendarData.nMonth + '-' + this.Lpad(num)
      }
      //console.info("calendarDataTime@@@", num, nDate)
      return nDate
    },


    /**
     * 说明：价格排期 - 获取某月份排期价格
     * @param num 索引
     */
    getScheduleData(num) {
      var nDate = this.calendarDataTime(num)
      var result = {}
      this.scheduleData.forEach((a, i) => {
        if (a.tourDate.indexOf(nDate) >= 0) {
          result = a
        }
      })
      return result
    },


    //--点击事件---------------------------------------------
    /**
     * 说明：价格排期 - 上切排期月份
     */
    prevBtn() {
      //console.info('prevBtn@@@@', this.mySwiper1)
      //this.mySwiper1.swipePrev()
      console.info('prevBtn')
    },

    /**
     * 说明：价格排期 - 下切排期月份
     */
    nextBtn() {
      //console.info('nextBtn@@@@', this.mySwiper1)
      //this.mySwiper1.swipeNext()
      console.info('nextBtn')
    },

    /**
     * 说明：价格排期 - 价格选择
     * @param obj 
     */
    SelectSchedule(num) {
      var o = this.getScheduleData(num)
      if (!o.price) {
        this.calendarActive = -1
        return;
      }

      this.calendarActive = num
      var s = 0
      this.scheduleData.forEach((x, i) => { 
        if (x.tourDate == o.tourDate) {
          s = i
        }
      })
      //console.info("handleSelectSchedule@", s, o);
      // var product = {
      //   productName: this.ProductInfo.Number + '【' + this.ProductInfo.Sub + '】' + this.ProductInfo.ProductName,
      //   productNum: this.ProductInfo.ArticleId,
      // }
      
      this.$emit('SelectSchedule', s, o);

      // Object.assign(this.ordersForm, obj, product)

      // 右边的下拉列表
      // this.tourSelectData.forEach(item => {
      //   if (item.indexOf(obj.date) > -1) {
      //     this.current_month = item
      //   }
      // })

      // this.fly_animation()
    },

    /**
     * 说明：计算某年某月的天数
     * @param year
     * @param month
     */
    getDayNum(year, month) {
      var veadar = !Boolean(2016 % 400) || !Boolean(year % 4) && year % 100
      var num
      switch (month) {
        case 2:
          num = veadar ? 29 : 28
          break
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
          num = 31
          break
        default:
          num = 30
      }
      return num
    },

    /**
     * 说明：左填充，默认以"0"填充，填充后长度默认2
     * @param obj 
     */
    Lpad(strSrc, strPad, len) {
        strSrc = strSrc + ''
        if (strPad == null) strPad = '0'
        if (len == null) len = 2
        while (strSrc.length < len) strSrc = strPad + strSrc
        return strSrc
    },

    fly_animation() {
      setTimeout(() => { this.scheduleActive = true }, 100)
      setTimeout(() => { this.scheduleActive = false }, 300)
      setTimeout(() => { this.scheduleActive = true }, 500)
      setTimeout(() => { this.scheduleActive = false }, 700)
    },

    /**
     * 订单提交前相关参数校验
     *
     * @param {Object} t
     */
    CheckStock(t) {
      if (this.ordersForm.adultNum <= 0) {
        this.ordersForm.adultNum = 1
      }
      if (this.ordersForm.childNum <= 0) {
        this.ordersForm.childNum = 0
      }
      //未选排期
      if (this.current_month === '请选择') {
        this.fly_animation()
        return false
      }
      
      this.hiddenGoodsForm = false
    },

    /**
     * 订单提交
     */
    GetStock() {
      // http://tourlogic.uzai.com/api/product/CheckStock
      
      var e, a = $('.select_left .selected_m .active')
      e = '1' === $.trim($('#lineSource').val()) ? JSON.stringify({
          productCode: a.attr('data-supproductcode'),
          compCode: a.attr('data-compcode')
      }) : JSON.stringify({
          productCode: a.attr('data-tuanno'),
          compCode: ''
      }), api.post('http://tourlogic.uzai.com/api/product/CheckStock', e, function (e) {
          null !== e && t(200 === e.ErrorCode ? e.JsonResult : 0)
      })
    },

  },
};
</script>
<style lang="scss">
.calendar-box {
  .day-list .new{
    text-align: center;
  }
}
.jg {
  font-weight: bold;
  font-size: 13px;
  margin: 2px 1px;
}
</style>
